/*
 * Copyright (c) 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.libermundi.tapestry.elfinder.services.impl;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.libermundi.tapestry.elfinder.services.Volume;
import org.libermundi.tapestry.elfinder.services.VolumeSource;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * @author Martin Papy
 *
 */
public class VolumeSourceImpl implements VolumeSource {
	private Map<String, Volume> _volumes = Maps.newHashMap();
	
	private Volume _defaultVolume;
	
	public VolumeSourceImpl(List<Volume> volumes){
		for (Volume volume : volumes) {
			add(volume);
		}
	}

	/* (non-Javadoc)
	 * @see org.libermundi.tapestry.elfinder.services.VolumeSource#add(org.libermundi.tapestry.elfinder.services.Volume)
	 */
	@Override
	public void add(Volume volume) {
		_volumes.put(volume.getId(), volume);
		if(_defaultVolume == null){
			_defaultVolume = volume;
		}
	}

	/* (non-Javadoc)
	 * @see org.libermundi.tapestry.elfinder.services.VolumeSource#add(org.libermundi.tapestry.elfinder.services.Volume, boolean)
	 */
	@Override
	public void add(Volume volume, boolean isdefault) {
		add(volume);
		if(isdefault){
			_defaultVolume = volume;
		}
	}

	/* (non-Javadoc)
	 * @see org.libermundi.tapestry.elfinder.services.VolumeSource#setDefault(org.libermundi.tapestry.elfinder.services.Volume)
	 */
	@Override
	public void setDefault(Volume volume) {
		Volume vol  = _volumes.get(volume.getId());
		if(vol == null){
			add(volume,Boolean.TRUE);
		} else {
			_defaultVolume = vol;
		}
	}

	/* (non-Javadoc)
	 * @see org.libermundi.tapestry.elfinder.services.VolumeSource#getVolumes()
	 */
	@Override
	public List<Volume> getVolumes() {
		Collection<Volume> col = _volumes.values();
		return Lists.newArrayList(col);
	}

	/* (non-Javadoc)
	 * @see org.libermundi.tapestry.elfinder.services.VolumeSource#getVolumeFromHash(java.lang.String)
	 */
	@Override
	public Volume getVolumeFromHash(String targetHash) {
		String volumeId = targetHash.substring(0, targetHash.indexOf("_"));
		return _volumes.get(volumeId);
	}

	/* (non-Javadoc)
	 * @see org.libermundi.tapestry.elfinder.services.VolumeSource#getDefaultVolume()
	 */
	@Override
	public Volume getDefaultVolume() {
		return _defaultVolume;
	}

}
